package com.jrx.anytxn.reporting.job.xib.step;

import com.alibaba.fastjson.JSONObject;
import com.jrx.anytxn.common.uitl.DateUtils;
import com.jrx.anytxn.customer.entity.CmCustomerSecondLevel;
import com.jrx.anytxn.customer.service.ICustomerService;
import com.jrx.anytxn.number.service.ISegmentService;
import com.jrx.anytxn.param.entity.FreeInterestVo;
import com.jrx.anytxn.param.entity.PrOrganizationTable;
import com.jrx.anytxn.param.mapper.ext.ExtFreeInterestMapper;
import com.jrx.anytxn.param.service.system.IOrganizationTableService;
import com.jrx.anytxn.param.utils.BizTypeProducts;
import com.jrx.anytxn.reporting.constant.ReportingConstant;
import com.jrx.anytxn.reporting.entity.TlFreeInterestTable;
import com.jrx.anytxn.transaction.constant.TransBizConstant;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.batch.item.ItemProcessor;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Arrays;
import java.util.Date;
import java.util.List;

/**
 * @comment: 免息成本报表Processor
 * @author: liuzb
 * @date: 2021/9/22 15:00
 */
@Service
public class FreeInterestReportingProcessor implements ItemProcessor<TlFreeInterestTable, TlFreeInterestTable> {

    @Autowired
    private IOrganizationTableService organizationTableService;
    @Autowired
    private ISegmentService iSegmentService;
    @Autowired
    private ExtFreeInterestMapper extFreeInterestMapper;
    @Autowired
    private ICustomerService iCustomerService;


    private static Logger logger = LoggerFactory.getLogger(FreeInterestReportingListener.class);


    @Override
    public TlFreeInterestTable process(TlFreeInterestTable fit) throws Exception {
        try {
            if (fit == null) {
                return null;
            }
            PrOrganizationTable org = organizationTableService.findByOrgIdForBatch(ReportingConstant.DEFAULT_ORG_NUMBER);
            // 获取当前系统日期
            Date today = org.getToday();
            TlFreeInterestTable fi = new TlFreeInterestTable();
            BeanUtils.copyProperties(fit, fi);
            //租户id
            fi.setId(iSegmentService.getId("TlFreeInterestTable"));
            //数据日期
            fi.setBusinessDate(today);
            // 还款日--到期日期所在月份的还款日 还款日=宽限期第一天=10号往前推一天
            Date paymentDay = DateUtils.getThisMonthDate(fit.getLastPaymentDate(), 9);
            // 已免息天数
            long freeDays = 0;
            // 剩余免息期天数
            long remainFreeDays = 0;
            // 在还款日之前
            // 还款日之后 在10/11/12/13结清的都不算逾期
            // 还在宽限期内--4天 （当前日期-借据开始日期+1）   --当前日期包含了已过宽限期天数
            // 结清
            boolean settles = Arrays.asList(ReportingConstant.ACCOUNT_STATUS_6, ReportingConstant.ACCOUNT_STATUS_7,
                    ReportingConstant.ACCOUNT_STATUS_8).contains(fi.getAccountStatus());
            // 跟13号做比较
            int compare13 = DateUtils.compare(today, DateUtils.addDay(paymentDay, 4));
            // 在12号（包含12号）不管结清没结清都享受免息期
            if (compare13 < 0) {
                freeDays = DateUtils.getDatePoor(today, fi.getPostingDate()) + 1;
                remainFreeDays = DateUtils.getDatePoor(paymentDay, today);
            } else if (compare13 == 0 && settles) {
                // 在13号内（包含13号）结清的不算罚息，免息天数继续加天数
                freeDays = DateUtils.getDatePoor(today, fi.getPostingDate()) + 1;
            } else {
                // （还款日-借据开始日期+1）
                freeDays = DateUtils.getDatePoor(paymentDay, fi.getPostingDate()) + 1;
            }
            CmCustomerSecondLevel secondLevel = iCustomerService.getSecondByChannelAndCustomerIdAndTensnId( TransBizConstant.DEFAULT_CHANNEL_NO, fit.getCustomerId(), fit.getTenantId(), BizTypeProducts.XAH_PRODUCT);

            if (StringUtils.isNotBlank(secondLevel.getBankOrgNo())) {
                logger.info("查询的参数1:{},参数2:{}", fi.getBankOrgNo(), fi.getTenantId());
                // 获取银行机构信息
                List<FreeInterestVo> list = extFreeInterestMapper.getBankInstInfo(fi.getBankOrgNo(), fi.getTenantId());
                logger.info("获取银行机构信息list:{}", JSONObject.toJSON(list));
                if (CollectionUtils.isNotEmpty(list)) {
                    FreeInterestVo tl = list.get(0);
                    fi.setBankName(tl.getBankName());
                    fi.setBankCode(tl.getBankCode());
                    fi.setBankOrgName(tl.getBankOrgName());
                }
            }
            // 已免息天数
            fi.setFreeDays(freeDays > 0 ? (int) freeDays : 0);
            // 剩余免息期天数
            fi.setRemainFreeDays(remainFreeDays > 0 ? (int) remainFreeDays : 0);
            fi.setSubjectId("11400301");
            fi.setSubjectName("个人贷款-个人消费贷款-成本");
            fi.setFtp("");
            fi.setFtpPay("");
            fi.setCreateTime(new Date());
            return fi;
        } catch (Exception e) {
            e.printStackTrace();
            logger.error("xibFreeInterestReportingJob 出错了：{}", e.getMessage());
        }
        return null;
    }
}
